package com.yuwubao.uav.tool.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.yuwubao.framework.bean.JsonResult;
import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <Description> <br>
 *
 * @author wk <br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2018/3/22 <br>
 * @see com.yuwubao.uav.tool.util <br>
 * @since V1.0<br>
 */
public class StringUtil {

    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateRandomString() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    public static synchronized String generateRandom(String prefix) {
        StringBuffer orderNo = new StringBuffer();
        orderNo.append(prefix); //默认 前缀 [Shop OrdeR]
        orderNo.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"))); //时间戳
        orderNo.append((int) ((Math.random() * 9 + 1) * 100000)); //6位随机数
        return orderNo.toString();
    }

    /**
     * 获取当前时间戳，单位秒
     *
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 将以逗号分隔的字符串转换成字符串数组
     *
     * @param valStr
     * @return String[]
     */
    public static String[] StrList(String valStr) {
        int i = 0;
        String TempStr = valStr;
        String[] returnStr = new String[valStr.length() + 1 - TempStr.replace(",", "").length()];
        valStr = valStr + ",";
        while (valStr.indexOf(',') > 0) {
            returnStr[i] = valStr.substring(0, valStr.indexOf(','));
            valStr = valStr.substring(valStr.indexOf(',') + 1, valStr.length());

            i++;
        }
        return returnStr;
    }

    /**
     * 功能描述:随机生成六位验证码
     *
     * @return
     */
    public static String generateAuthCode() {
        Integer authCode = (int) ((Math.random() * 9 + 1) * 100000);
        return authCode.toString();
    }

    /**
     * 功能描述：判断是否是数字
     */
    public static boolean checkIfNumber(String str) {
        boolean isNumber = false;
        Pattern pattern = Pattern.compile("[0-9]{1,}");
        Matcher matcher = pattern.matcher((CharSequence) str);
        if (matcher.matches()) {
            isNumber = true;
        }
        return isNumber;
    }

    /**
     * 功能描述：判断是否是大于0整形数字
     */
    public static boolean checkIfIntNumber(String str) {
        boolean isNumber = false;
        Pattern pattern = Pattern.compile("[1-9][0-9]{0,}");
        Matcher matcher = pattern.matcher((CharSequence) str);
        if (matcher.matches()) {
            isNumber = true;
        }
        return isNumber;
    }

    /**
     * 功能描述：判断是否是经纬度
     */
    public static boolean checkIfLatlong(String str) {
        boolean isNumber = false;
        Pattern pattern = Pattern.compile("(-|\\+)?(180\\.0{4,14}|(\\d{1,2}|1([0-7]\\d))\\.\\d{4,14})");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            isNumber = true;
        }
        return isNumber;
    }


    /**
     * 功能描述：判断是否是int(6)
     */
    public static boolean checkIntSix(String str) {
        boolean isNumber = false;
        Pattern pattern = Pattern.compile("([1-9]\\d{1,5})");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            isNumber = true;
        }
        return isNumber;
    }



    /**
     * 功能描述：判断是否是经纬度初始值
     */
    public static boolean checkIfLatlongInit(String str) {
        boolean isNumber = false;
        Pattern pattern = Pattern.compile("(0\\.0{1,14})");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            isNumber = true;
        }
        return isNumber;
    }

    /**
     * 判断一个对象是否为空
     */
    public static boolean isNvlOrBlank(Object o) {
        if (o == null) {
            return true;
        } else {
            String oStr = o.toString().replaceAll(" ", "");
            if (oStr.toString().equals("")) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 判断一个对象是否为空
     */
    public static boolean isNotNvlOrBlank(Object o) {
        return !isNvlOrBlank(o);
    }

    /**
     * 字符串全局替换
     */
    public static final String replace(String line, String oldString, String newString) {
        if (line == null) {
            return null;
        }
        int i = 0;
        if ((i = line.indexOf(oldString, i)) >= 0) {
            char[] line2 = line.toCharArray();
            char[] newString2 = newString.toCharArray();
            int oLength = oldString.length();
            StringBuffer buf = new StringBuffer(line2.length);
            buf.append(line2, 0, i).append(newString2);
            i += oLength;
            int j = i;
            while ((i = line.indexOf(oldString, i)) > 0) {
                buf.append(line2, j, i - j).append(newString2);
                i += oLength;
                j = i;
            }
            buf.append(line2, j, line2.length - j);
            return buf.toString();
        }
        return line;

    }

    /**
     * 把版本号转换为int值
     */
    public static final Integer convertVerToValue(String verStr) {
        String[] versionArr = verStr.toString().split("\\.");
        int vLength = versionArr.length;
        int versionValue = 0;
        if (vLength == 1) {
            versionValue = Integer.valueOf(versionArr[0]) * 10 * 10;
        } else if (vLength == 2) {
            versionValue = Integer.valueOf(versionArr[0]) * 10 * 10 + Integer.valueOf(versionArr[1]) * 10;

        } else if (vLength == 3) {
            versionValue = Integer.valueOf(versionArr[0]) * 10 * 10 + Integer.valueOf(versionArr[1]) * 10
                    + Integer.valueOf(versionArr[2]);
        }
        return versionValue;
    }


    /**
     * 功能描述：判断是否是字母数字的字符串
     */
    public static boolean checkIfNumChar(String str) {
        boolean isNumber = false;
        Pattern pattern = Pattern.compile("^[a-zA-Z0-9]+$");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            isNumber = true;
        }
        return isNumber;
    }

    /**
     * 功能描述：判断是否是以逗号分隔的字符串
     */
    public static boolean checkIfMulStr(String str) {
        boolean isNumber = false;
        Pattern pattern = Pattern.compile("^([a-zA-Z0-9]+,*)+$");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            isNumber = true;
        }
        return isNumber;
    }

    /**
     * 功能描述：根据地块边界点获取地块类型
     */
    public static String getFieldTypeByBorder(String str) {
        String fieldType = "";
        fieldType = str.substring(0, str.indexOf(';'));
        fieldType = str.substring(str.lastIndexOf(",")+1);
        return fieldType;
    }



    public static void main(String[] args) {
    }

    /**
     * 校验是否匹配正则
     * @param regExp
     * @param value
     */
    public static boolean regularCheck(String regExp, String value){
        Pattern pattern=Pattern.compile(regExp);
        Matcher matcher= pattern.matcher(value);
        return matcher.matches();
    }

    /**
     * 校验排序字段和规则是否合法
     * @param
     * @param
     */
    public static boolean sortKeysAndRulesCheck(JsonResult jsonResult, String sortKeys, String sortRules, String[] fields) {
        if (!StringUtils.isEmpty(sortKeys)) {
            String[] ka = sortKeys.split(",");
            for (String s : ka) {
                boolean f = false;
                for (String ss : fields) {
                    if (s.equals(ss)) {
                        f = true;
                    }
                }
                if (!f) {
                    jsonResult.setCode(JsonResult.FAILURE_CODE);
                    jsonResult.setMessage("排序字段不合法");
                    return false;
                }
            }
        }

        if (!StringUtils.isEmpty(sortRules)) {
            String[] ra = sortRules.split(",");
            for (String s : ra) {
                if (!"asc".equalsIgnoreCase(s) && !"desc".equalsIgnoreCase(s)) {
                    jsonResult.setCode(JsonResult.FAILURE_CODE);
                    jsonResult.setMessage("排序规则只能是asc或者desc");
                    return false;
                }
            }
        }

        if (!StringUtils.isEmpty(sortKeys) && !StringUtils.isEmpty(sortRules)) {
            String[] ka = sortKeys.split(",");
            String[] ra = sortRules.split(",");
            if (ka.length != ra.length) {
                jsonResult.setCode(JsonResult.FAILURE_CODE);
                jsonResult.setMessage("排序字段个数和排序规则个数不匹配");
                return false;
            }

            //组装排序SQL
            String sql = "";
            for (int i = 0; i < ka.length; i++) {
                sql += ka[i] + " " + ra[i] + ",";
            }

            sql = sql.substring(0, sql.length() - 1);
            jsonResult.setResult(sql);
            jsonResult.setCode(JsonResult.SUCCESS_CODE);
        }

//		if ((StringUtils.isEmpty(sortKeys) && !StringUtils.isEmpty(sortRules)) ||
//				(!StringUtils.isEmpty(sortKeys) && StringUtils.isEmpty(sortRules))) {
//			jsonResult.setCode(JsonResult.FAILURE_CODE);
//			jsonResult.setMessage("排序字段个数和排序规则个数不匹配");
//			return false;
//		}

        return true;
    }

    public static boolean dateFormatCheck(JsonResult jsonResult, String beginDate, String endDate){
        Pattern pattern = Pattern.compile("((^((1[8-9]\\d{2})|([2-9]\\d{3}))([-])(10|12|0?[13578])([-])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-])(11|0?[469])([-])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-])(0?2)([-])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-])(0?2)([-])(29)$)|(^([3579][26]00)([-])(0?2)([-])(29)$)|(^([1][89][0][48])([-])(0?2)([-])(29)$)|(^([2-9][0-9][0][48])([-])(0?2)([-])(29)$)|(^([1][89][2468][048])([-])(0?2)([-])(29)$)|(^([2-9][0-9][2468][048])([-])(0?2)([-])(29)$)|(^([1][89][13579][26])([-])(0?2)([-])(29)$)|(^([2-9][0-9][13579][26])([-])(0?2)([-])(29)$))");
//		Pattern pattern = Pattern.compile("((^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(10|12|0?[13578])([-\\/\\._])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(11|0?[469])([-\\/\\._])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(0?2)([-\\/\\._])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([3579][26]00)([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][0][48])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][0][48])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][2468][048])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][2468][048])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][13579][26])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][13579][26])([-\\/\\._])(0?2)([-\\/\\._])(29)$))");
        if (!StringUtils.isEmpty(beginDate)) {
            Matcher matcher1 = pattern.matcher(beginDate);
            if (!matcher1.matches()) {
                jsonResult.setCode(JsonResult.FAILURE_CODE);
                jsonResult.setMessage("开始时间格式不正确");
                return false;
            }
        }

        if (!StringUtils.isEmpty(endDate)) {
            Matcher matcher2 = pattern.matcher(endDate);
            if (!matcher2.matches()) {
                jsonResult.setCode(JsonResult.FAILURE_CODE);
                jsonResult.setMessage("结束时间格式不正确");
                return false;
            }
        }

        if (!StringUtils.isEmpty(endDate) && !StringUtils.isEmpty(beginDate)) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date d1 = sf.parse(beginDate);
                Date d2 = sf.parse(endDate);
                if(d1.after(d2)){
                    jsonResult.setCode(JsonResult.FAILURE_CODE);
                    jsonResult.setMessage("开始时间不能大于结束时间");
                    return false;
                }
            } catch (ParseException e) {
                e.printStackTrace();
                jsonResult.setCode(JsonResult.FAILURE_CODE);
                jsonResult.setMessage("开始或者结束时间格式不正确");
                return false;
            }
        }

        return true;
    }

    public static boolean doubleFormatCheck(JsonResult jsonResult, String minAmount, String maxAmount){
        Pattern pattern = Pattern.compile("^([1-9]\\d{0,9}(\\.\\d{1,2})?)|0|(0\\.\\d{1,2})$");
        if (!StringUtils.isEmpty(minAmount)) {
            Matcher matcher1 = pattern.matcher(minAmount);
            if (!matcher1.matches()) {
                jsonResult.setCode(JsonResult.FAILURE_CODE);
                jsonResult.setMessage("最小金额格式不正确");
                return false;
            }
        }
        if (!StringUtils.isEmpty(maxAmount)) {
            Matcher matcher2 = pattern.matcher(maxAmount);
            if (!matcher2.matches()) {
                jsonResult.setCode(JsonResult.FAILURE_CODE);
                jsonResult.setMessage("最大金额格式不正确");
                return false;
            }
        }

        if (!StringUtils.isEmpty(minAmount) && !StringUtils.isEmpty(maxAmount)) {
            try {
                Double d1 = Double.valueOf(minAmount);
                Double d2 = Double.valueOf(maxAmount);
                if(d1 > d2){
                    jsonResult.setCode(JsonResult.FAILURE_CODE);
                    jsonResult.setMessage("最小金额不能大于最大金额");
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                jsonResult.setCode(JsonResult.FAILURE_CODE);
                jsonResult.setMessage("最小金额或者最大金额格式不正确");
                return false;
            }
        }


        return true;
    }

    /**
     * 根据服务点id生成预约单code
     * @param servsId
     * @param uuidLength
     * @return
     */
    public static String createAppoCode(String servsId, int uuidLength){
        //规则C + XXX(3位服务点id) + UUID.randomUUID()
        StringBuffer orderCode = new StringBuffer();
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        uuid = uuid.toUpperCase();
        int servsIdLength = 4;
        orderCode.append("C");
        if (!StringUtils.isEmpty(servsId)) {
            if (servsId.length() < servsIdLength) {
                orderCode.append("0000".substring(0, servsIdLength - servsId.length())).append(servsId);
            } else {
                orderCode.append(servsId);
            }
        }
        orderCode.append(uuid.substring(0, uuidLength));
        return orderCode.toString();
    }


    /**
     * 判断是否是一个IP
     * @param IP
     * @return
     */
    public static boolean isIp(String IP){
        boolean b = false;
        if(IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")){
            b = true;
        }
        return b;
    }


    /**
     * IP截断
     * @param ip
     * @return
     */
    public static String shortIpInfo(String ip){
        String shortIpInfo = ip;
        if(ip.indexOf(".") >= 0){
            shortIpInfo = ip.substring(ip.indexOf(".")+1).replaceAll("\\.", "");
        }else{
            int ipLen = ip.length();
            if(ipLen > 11){
                shortIpInfo = shortIpInfo.substring(shortIpInfo.length()-11);
            }
        }
        return shortIpInfo;
    }

    /**
     * 截取经纬度，保留n位小数
     * @param value
     * @return
     */
    public static String shortCutLngLat(String value, int numLen){
        if(StringUtil.isNotNvlOrBlank(value)){
            int pointIndex = value.indexOf(".");
            String headLng = value.substring(0, pointIndex);
            String shortLng = value.substring(pointIndex+1);
            if(shortLng.length()>numLen){
                shortLng = shortLng.substring(0, numLen);
            }
            value = headLng +"." +shortLng;
        }
        return value;
    }

    /**
     * 生成短UUID
     * @return
     */
    public static String shortUUID(){
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString();
        return uuidStr.substring(uuidStr.lastIndexOf("-") + 1);
    }

    /**
     * 将指定byte数组转换为带中划线的mac地址
     * @return void
     */
    public static String convertHexToMac(byte[] b)
    {
        if(b.length < 8){
            return "";
        }

        String prefix = "";
        // 检查前缀
        for (int i = 0; i < 2; i++)
        {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1)
            {
                hex = '0' + hex;
            }
            prefix = prefix + hex.toLowerCase();
        }
        if(!prefix.equalsIgnoreCase("A55A")){
            return "";
        }

        String macStr = "";
        for (int i = 2; i < 8; i++)
        {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1)
            {
                hex = '0' + hex;
            }
            macStr = macStr + hex.toLowerCase() + '-';
        }
        return macStr.substring(0, macStr.lastIndexOf('-'));
    }

    /**
     * 将指定byte数组转换为16进制的形式
     * @param b byte[]
     * @return void
     */
    public static String convertHexString(byte[] b)
    {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
        {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1)
            {
                hex = '0' + hex;
            }
            resultSb.append(hex.toUpperCase() + " ");
        }
        return resultSb.toString();
    }


    /**
     * 判断是否是JSON数组格式
     * @param json
     * @return void
     */
    public static boolean isJsonAry(String json) {
        if (StringUtils.isBlank(json)) {
            return false;
        }
        try {
            JSONArray.parseArray(json);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 将指定byte数组以16进制的形式打印到控制台
     * @param b byte[]
     * @return void
     */
    public static void printHexString(byte[] b)
    {
        for (int i = 0; i < b.length; i++)
        {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1)
            {
                hex = '0' + hex;
            }
            System.out.print(hex.toUpperCase() + " ");
        }
        System.out.println("");
    }

    /**
     * 高位补0
     * @param value
     * @param length
     * @return
     */
    public static String zeroFill(int value, int length){
        String initStr = "";
        for(int i =0;i<length;i++){
            initStr = initStr + "0";
        }
        DecimalFormat df = new DecimalFormat(initStr);
        return df.format(value);
    }

}
